package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"strings"

	"github.com/lxn/walk"
	. "github.com/lxn/walk/declarative"
)

var myAction *walk.Action

var myWindow *MyMainWindow

var excelExtension = []string{"xlam", "xlsm", "xlsx", "xltm", "xltx"}

type MyMainWindow struct {
	*walk.MainWindow
	te *walk.TextEdit

	model    *EnvModel
	FileList []string

	listBox *walk.ListBox
}

func (mw *MyMainWindow) show() {
	text := ""
	for _, file := range mw.FileList {
		text += file
		text += "\r\n"
	}
	mw.te.SetText(text)
}

func (mw *MyMainWindow) lb_ItemActivated() {
	value := mw.model.items[mw.listBox.CurrentIndex()].value
	index, exist := mw.FileExist(value)
	if exist {
		mw.DeleteFile(index)
	} else {
		mw.FileList = append(mw.FileList, value)
	}
	mw.show()
}

func (mw *MyMainWindow) SelectAll() {
	mw.FileList = make([]string, 0)
	for _, item := range mw.model.items {
		mw.FileList = append(mw.FileList, item.value)
	}
	mw.show()
}

func (mw *MyMainWindow) FileExist(filename string) (int, bool) {
	for index, file := range mw.FileList {
		if file == filename {
			return index, true
		}
	}
	return 0, false
}

func (mw *MyMainWindow) DeleteFile(index int) {
	mw.FileList = append(mw.FileList[:index], mw.FileList[index+1:]...)
}

type EnvItem struct {
	name  string
	value string
}

type EnvModel struct {
	walk.ListModelBase

	items []EnvItem
}

func NewEnvModel() *EnvModel {
	pwd, _ := os.Getwd()
	files, err := ioutil.ReadDir(pwd)
	if err != nil {
		log.Fatal(err)
	}
	m := &EnvModel{items: make([]EnvItem, 0)}
	for _, file := range files {
		for _, ext := range excelExtension {
			if strings.HasSuffix(file.Name(), ext) && (!strings.HasPrefix(file.Name(), "~$")) {
				m.items = append(m.items, EnvItem{file.Name(), file.Name()})
				break
			}
		}

	}
	return m
}

func (m *EnvModel) ItemCount() int {
	return len(m.items)
}

func (m *EnvModel) Value(index int) interface{} {
	return m.items[index].name
}

func ShowMsgBox(title, msg string) int {
	return walk.MsgBox(myWindow, title, msg, walk.MsgBoxOK)
}

func TiggerFunc() {
	ShowMsgBox("天降惊喜", "你要死了")
}

func main() {
	defer func() {
		if err := recover(); err != nil {
			errMsg := fmt.Sprintf("%#v", err)
			ioutil.WriteFile("fuck.log", []byte(errMsg), 0644)
		}
	}()

	myWindow = &MyMainWindow{model: NewEnvModel(), FileList: make([]string, 0)}
	if _, err := (MainWindow{
		AssignTo: &myWindow.MainWindow,
		Title:    "燕燕工具箱",
		MinSize:  Size{600, 400},
		Layout:   VBox{},
		Children: []Widget{
			HSplitter{
				MinSize: Size{600, 300},
				Children: []Widget{
					ListBox{
						StretchFactor: 1,
						AssignTo:      &myWindow.listBox,
						Model:         myWindow.model,

						OnItemActivated: myWindow.lb_ItemActivated,
					},
					TextEdit{
						StretchFactor: 1,
						AssignTo:      &myWindow.te,
						ReadOnly:      true,
						Text:          "双击左侧文件名，选择要合并的文件。\r\n再次双击，可取消文件\r\n左侧文件列表仅显示支持的excel文件\r\n仅仅支持以下后缀：xlam,xlsm,xlsx,xltm,xltx",
					},
				},
			},
			HSplitter{
				MaxSize: Size{600, 50},
				Children: []Widget{
					PushButton{
						StretchFactor: 8,
						Text:          "全选",
						OnClicked: func() {
							myWindow.SelectAll()
						},
					},
					PushButton{
						StretchFactor: 8,
						Text:          "合并",
						OnClicked: func() {
							msg := "合并完成"
							err := Merge(myWindow.FileList)
							if err != nil {
								msg = err.Error()
							}
							ShowMsgBox("天降惊喜", msg)
						},
					},
				},
			},
		},
	}.Run()); err != nil {
		log.Fatal(err)
	}
}
